import path from 'node:path';

import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
import legacy from '@vitejs/plugin-legacy';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { visualizer } from 'rollup-plugin-visualizer';
import { Config } from 'svgo';
import AutoImport from 'unplugin-auto-import/vite';
import { TDesignResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { defineConfig, loadEnv } from 'vite';
import eslint from 'vite-plugin-eslint';
import { createHtmlPlugin } from 'vite-plugin-html';
// import viteImagemin from 'vite-plugin-imagemin';
import { viteMockServe } from 'vite-plugin-mock';
import removeConsole from 'vite-plugin-remove-console';
import svgLoader from 'vite-svg-loader';

import Package from './package.json';

const CWD = process.cwd();

const svgoConfig: Config = {
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          // customize default plugin options
          inlineStyles: {
            onlyMatchedOnce: false
          },

          // or disable plugins
          removeDoctype: false,
          removeViewBox: false // ViewBox默认不删除
        }
      }
    },
    {
      name: 'removeAttrs',
      params: { attrs: ['svg:width', 'svg:height'] } // 删除指定节点的属性
    },
    'convertStyleToAttrs', // 将样式转换为属性
    'removeStyleElement', // 删除 <style> 元素
    'prefixIds' // 用文件名或其他任意字符串作为元素 ID 和类名的前缀。
  ]
};

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const { VITE_BASE_URL, VITE_BASE_API, VITE_PROXY_URL } = loadEnv(
    mode,
    CWD,
    ''
  );
  return {
    base: VITE_BASE_URL,
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '~': path.resolve(__dirname, './')
      },
      extensions: ['.vue', '.ts', '.tsx', '.js', 'jsx', '.json']
    },
    optimizeDeps: {
      include: ['vue', 'vue-router', 'axios', 'pinia']
    },
    define: {
      // 'process.env': JSON.stringify({
      //   VERSION: Package.version
      // })
    },
    css: {
      modules: {
        localsConvention: 'camelCase' // 默认只支持驼峰，修改为同时支持横线和驼峰
      },
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: `@import "@/style/mixins.scss";@import "@/style/variables.scss";`
        }
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (/[\\/]node_modules[\\/]_?uuid[\\/]/.test(id)) {
              return 'uuid';
            }
            if (/[\\/]node_modules[\\/]_?dayjs[\\/]/.test(id)) {
              return 'dayjs';
            }
            if (/[\\/]node_modules[\\/]_?tdesign-vue-next[\\/]/.test(id)) {
              return 'tdesign-vue-next';
            }
            if (
              /[\\/]node_modules[\\/]_?tdesign-icons-vue-next[\\/]/.test(id)
            ) {
              return 'tdesign-icons-vue-next';
            }
            if (/[\\/]node_modules[\\/]_?lodash(-es)?[\\/]/.test(id)) {
              return 'lodash';
            }
          }
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      viteMockServe({
        mockPath: 'mock',
        watchFiles: true,
        enable: mode === 'mock'
      }),
      svgLoader({ svgoConfig }),
      eslint({
        exclude: ['**/node_modules/**', 'dist/**', 'public/**']
      }),
      AutoImport({
        eslintrc: {
          enabled: true
        },
        vueTemplate: true,
        imports: [
          'vue',
          'vue-router',
          'pinia',
          '@vueuse/core',
          {
            axios: [
              // default imports
              ['default', 'axios'] // import { default as axios } from 'axios',
            ]
          }
        ],
        resolvers: [
          TDesignResolver({
            library: 'vue-next'
          })
        ]
      }),
      Components({
        dts: true,
        resolvers: [
          TDesignResolver({
            library: 'vue-next',
            resolveIcons: true
          }),
          {
            type: 'directive',
            resolve: name => {
              if (name === 'Loading') {
                return {
                  name: 'vLoading',
                  from: `tdesign-vue-next/es/${name.toLocaleLowerCase()}/directive`
                };
              }
              return undefined;
            }
          }
        ]
        // resolvers: [
        // 自定义自动引入规则
        //   {
        //     // 自定义图标库tdesign-icons-vue-next导入方式
        //     // tdesign组件按需导入部分组件无法生效，解决方案未知（目前已知<t-option/>无法使用）
        //     type: 'component',
        //     resolve: (name: string) => {
        //       if (/[a-z0-9]+Icon$/.test(name)) {
        //         return {
        //           name,
        //           from: `tdesign-icons-vue-next`
        //         };
        //       }
        //       return undefined;
        //     }
        //   }
        // ]
      }),
      removeConsole(),
      legacy(),
      visualizer({
        emitFile: false,
        gzipSize: true,
        filename: 'report.html'
      }),
      // viteImagemin({
      //   gifsicle: {
      //     optimizationLevel: 7,
      //     interlaced: false
      //   },
      //   optipng: {
      //     optimizationLevel: 7
      //   },
      //   mozjpeg: {
      //     quality: 20
      //   },
      //   pngquant: {
      //     quality: [0.8, 0.9],
      //     speed: 4
      //   },
      //   svgo: {
      //     plugins: svgoConfig.plugins as any[]
      //   }
      // }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            title: Package.name,
            keywords: Package.keywords.join(),
            description: Package.description,
            author: Package.author
          }
        }
      }),
      command === 'build' && optimizeLodashImports()
    ].filter(Boolean),

    server: {
      port: 3003,
      host: '0.0.0.0',
      open: false, // 设置服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      warmup: {
        clientFiles: ['./index.html', './src/layouts/**/*.vue']
      },
      proxy: {
        // mock 代理地址
        [`^${VITE_BASE_API}/mock`]: {
          target: 'http://127.0.0.1:3003',
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp(`^${VITE_BASE_API}`), '')
        },
        // 远程代理地址
        [`^${VITE_BASE_API}`]: {
          target: VITE_PROXY_URL,
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp(`^${VITE_BASE_API}`), '')
        }
      }
    }
  };
});
